var express = require('express')
var router = express.Router()
const { getALL, getById, exec } = require('../db')

// 获取分页事件
router.post('/', async (req, res) => {
  // 解析请求参数
  const { page = 1, size = 5, content = '' } = req.body
  // 查询总条数
  if (content == '') {
    var sql = `select count(*) as total from gg_notice`
    var { total } = await getById(sql)
    // 定义偏移量
    var offset = (page - 1) * size
    // 重新编写sql语句
    sql = `select notice_id,notice_content,notice_time from gg_notice order by notice_id desc limit ${offset},${size}  `
    // 执行sql语句,获得结果
    var data = await getALL(sql)
  } else {
    var sql = `select count(*) as total from gg_notice where notice_content like '%${content}%'`
    var { total } = await getById(sql)
    // 定义偏移量
    var offset = (page - 1) * size
    // 重新编写sql语句
    sql = `select notice_id,notice_content,notice_time from gg_notice where notice_content like '%${content}%' order by notice_id desc limit ${offset},${size}  `
    // 执行sql语句,获得结果
    var data = await getALL(sql)
  }

  // 返回结果
  res.send({
    code: 201,
    message: '获取公告成功!',
    result: {
      total,
      data,
    },
  })
})

/* 添加公告 commonuser*/
router.post('/publish', async (req, res) => {
  console.log(req.body)
  //解析请求体
  const { userId, content } = req.body
  //操作数据库
  let sql1 = `insert into gg_notice(user_id,notice_content) values('${userId}','${content}')`
  // 二执行sql语句,获得结果
  const data = await exec(sql1)
  // 三返回数据
  res.send({
    code: 202,
    msg: '发布公告成功!',
  })
})

router.delete('/:id', async (req, res) => {
  const { id } = req.params
  console.log(id)
  let sql = `delete from gg_notice where notice_id =${id}`
  await exec(sql)
  // 三返回数据
  res.send({
    code: 203,
    msg: '删除公告成功!',
  })
})
module.exports = router
